<?php

namespace app\admin\logic;

use app\common\model\CarMoneyLog;
use app\common\model\Work;
use think\Db;

/**
 * Class WorkLogic
 * @package app\admin\logic
 *
 * 付款类型录入
 * 生成挂账单
 * 工单查询列表
 */
class WorkLogic
{
    function findOne($id)
    {
        $work = model('work')->with(['client', 'car', 'reception', 'repairman'])->find($id);
        switch ($work['car_vip']) {
            case 'C':
                $work['sale_discount'] = $work['sale'];
                break;
            case 'B':
                $work['sale_discount'] = $work['sale'] * 0.95;
                break;
            case 'A':
                $work['sale_discount'] = $work['sale'] * 0.9;
                break;
        }
        return $work;
    }

    /*
     * 条件查询客户
     */
    function query($where)
    {
        return model('work')->with(['client', 'reception', 'repairman', 'car'])->where($where)->order('work.date desc')->paginate(20);
    }

    function queryTotal($where = '', $q = '')
    {
        $work = model('work');
        $param = json_decode($q, true);

        $conditions = [];
        if (!empty($param['num'])) {
            $num = $param['num'];
            $conditions['num'] = array('like', "%$num%");
        }
        if (!empty($param['car_num'])) {
            $car_num = $param['car_num'];
            $conditions['car_num'] = array('like', "%$car_num%");
        }
        if (!empty($param['client_name'])) {
            $client_name = $param['client_name'];
            $conditions['client.name'] = array('like', "%$client_name%");
        }
        if (session('role') != 0) {
            $conditions['reception.branch_id'] = session('branch_id');
        }
        $total = $work->where($where)->where($conditions)->sum("total");

        return $total;
    }

    function queryJqGrid($where = '', $page = 1, $rows = 20, $q = '')
    {
        $work = model('work');
        $param = json_decode($q, true);

        $conditions = [];
        if (!empty($param['num'])) {
            $num = $param['num'];
            $conditions['num'] = array('like', "%$num%");
        }
        if (!empty($param['car_num'])) {
            $car_num = $param['car_num'];
            $conditions['car_num'] = array('like', "%$car_num%");
        }
        if (!empty($param['client_name'])) {
            $client_name = $param['client_name'];
            $conditions['client.name'] = array('like', "%$client_name%");
        }
        if (session('role') != 0) {
            $conditions['reception.branch_id'] = session('branch_id');
        }
        $pageInfo = $work->with(['client', 'reception', 'repairman'])->where($where)->where($conditions)->order('num desc')->paginate($rows);

        $data['total'] = $pageInfo->lastPage();
        $data['page'] = $pageInfo->currentPage();
        $data['rows'] = $pageInfo->items();

        return $data;
    }

    public function queryJqGridNoPaied($where = '', $page = 1, $rows = 10, $q = '')
    {
        return $this->queryJqGrid('paid_time is null and pay_result=0', $page, $rows, $q);

    }

    public function queryJqGridPaied($where = '', $page = 1, $rows = 10, $q = '')
    {

        return $this->queryJqGrid('paid_time is null and pay_result=1', $page, $rows, $q);
    }

    public function queryJqGridPayed($where = '', $page = 1, $rows = 10, $q = '')
    {

        return $this->queryJqGrid('paid_time is not null and pay_result=1', $page, $rows, $q);
    }

    public function queryJqGridNotify($where = '', $page = 1, $rows = 10, $q = '')
    {
        $sql = "SELECT
                    w.*,
                    c.address,
                    c.`name`,
                    c.phone,
                    c.remark,
                    c.type
                FROM
                    `work` w
                LEFT JOIN client c ON c.id = w.client_id
                WHERE
                    num IN (
                        SELECT
                            MAX(w.num) AS work_num
                        FROM
                            `work` w
                        WHERE
                            w.date BETWEEN DATE_ADD(
                                DATE_ADD(NOW(), INTERVAL - 5 MONTH),
                                INTERVAL - 7 DAY
                            )
                        AND DATE_ADD(NOW(), INTERVAL - 5 MONTH)
                        AND w.`enable` IS NULL
                        AND w.server_type=".session('branch_id')." 
                        GROUP BY
                            w.car_num
                    )
                ORDER BY
                    date DESC";
        $pageInfo = Db::query($sql);

        return $pageInfo;
    }

    public function getCount($type)
    {
        $sql = "";
        if ($type == "indexCount") {
            $sql = "SELECT COUNT(1) c FROM `work` w WHERE w.paid_time is null and w.pay_result=0 AND w.server_type=".session('branch_id');
        } else if ($type == "payCount") {
            $sql = "SELECT COUNT(1) c FROM `work` w WHERE w.paid_time IS NULL AND w.pay_result = 1 AND w.server_type=".session('branch_id');
        } else if ($type == "invoiceCount") {
            $sql = "SELECT
                        count(1) c
                    FROM
                        (
                            SELECT
                                MAX(w.num) AS work_num
                            FROM
                                `work` w
                            WHERE
                                w.date BETWEEN DATE_ADD(
                                    DATE_ADD(NOW(), INTERVAL - 5 MONTH),
                                    INTERVAL - 7 DAY
                                )
                            AND DATE_ADD(NOW(), INTERVAL - 5 MONTH)
                            AND w.`enable` IS NULL
                            AND w.server_type=".session('branch_id')." 
                            GROUP BY
                                w.car_num
                        ) tb";
        }
        return DB::query($sql)[0]['c'];
    }

    /*
     * 新增工单
     */
    function add($data)
    {
        if ($data['id'] > 0) {
            return model('work')->data($data)->allowField(true)->isUpdate(true)->save();
        } else {
            // 增加单号数值
            Db::query("update sequence set current_val=current_val+increment_val where seq_name='work_num';");
            $data['inserttime'] = time();
            $data['lastupdatetime'] = time();
            $data['server_type'] = session('branch_id');
            return model('work')->data($data)->allowField(true)->save();
        }
    }

    // 维修技师添加数据
    function addTech($param = '', $servers = '')
    {
        //更新工单数据
        $workData = json_decode($param, true);

        // 保存服务项目数据
        $serversData = json_decode($servers, true);

        $sale = 0;

        foreach ($serversData as $k => $v) {
            $v['work_id'] = $workData['id'];
            $v['price'] *= $v['num'];

            $sale += $v['price'];

            model('server')->data($v)->allowField(true)->isUpdate(false)->save();
            $gnum = $v['gnum'];
            Db::query("update goods set storage=storage-? where num=?", [$v['num'], $gnum]);
            // model('goods')->data($v)
            // 添加出库记录
            $data_chuku['goods_num'] = $gnum;
            $data_chuku['count'] = $v['num'];
            $data_chuku['user_id'] = session('id');
            $data_chuku['type'] = '出库';
            model('Glogs')->data($data_chuku)->allowField(true)->isUpdate(false)->save();

        }
        $workData['sale'] = $sale;

        $res = model('work')->data($workData)->allowField(true)->isUpdate(true)->save();

        return $res;
    }

    function del($id = 0)
    {
        return model('work')->destroy($id);
    }

    public function getLinkedClient($car_num)
    {
        $data = model('work')
            ->where('car_num', $car_num)
            ->order('date desc')
            ->limit(1)
            ->field('client_id')
            ->select();
        // p($data);
        if (!empty($data)) {
            $client = model('client')->find($data[0]['client_id']);
            return $client;
        }
        return null;
    }

    // 前台人员拿到维修技师单子后维护数据
    public function doModifyWork($param = '')
    {
        $workData = json_decode($param, true);
        $workData['pay_result'] = '1';

        $workData['lastupdatetime'] = time();
        $res = model('work')->data($workData)->allowField(true)->isUpdate(true)->save();

        return $res;
    }

    /*
     * 结账操作
     * @param string $param
     *
     * @return false|int
     */
    public function doPay($param = '')
    {
        $workData = json_decode($param, true);

        // 车牌号
        $carNum = $workData['car_num'];
        // 消费总额
        $total = $workData['total'];
        model('car')->where('car_num', $carNum)->setInc('moneyconsumption', $total);
        $moneyConsumption = model('car')->where('car_num', $carNum)->value('moneyconsumption');
        // 根据已消费的金额，修改会员等级
        $grade = 'C';
        if ($moneyConsumption >= 5000) {
            $grade = 'B';
        } else if ($moneyConsumption >= 10000) {
            $grade = 'A';
        }

        $moneyleft = model('car')->where('car_num', $carNum)->value('moneyleft');
        // 若消费金额为负数则忽略会员扣费操作
        if($total > 0){
            $moneyleft = $moneyleft > $total ? $moneyleft - $total : 0;
        }
        // 记录该车已消费记录
        model('car')->data(['car_num' => $carNum, 'vip' => $grade, 'moneyleft' => $moneyleft])->isUpdate(true)->save();

        $workData['pay_result'] = 1;
        $workData['paid_time'] = time();
        // 保存工单信息
        $res = model('work')->data($workData)->allowField(true)->isUpdate(true)->save();
        return $res;

    }

    public function doRecharge($param = '')
    {
        $data = json_decode($param, true);
        $car = model('car')->where('car_num', $data['car_num'])->find();
        // 记录余额更改日志
        $data['operateid'] = session('id');
        $data['inserttime'] = time();
        $data['moneyleft'] = $car['moneyleft'];
        // p($data);
        model('CarMoneyLog')->data($data)->allowField(true)->isUpdate(false)->save();

        // 保存会员余额信息
        $res = model('car')->where('car_num', $data['car_num'])->setInc('moneyleft', $data['charge']);
        return $res;
    }


}